package com.hyh.toyshopping.filters;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyh.toyshopping.commons.Result;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * @version 1.0
 * @BelongsProject:IntelliJ IDEA
 * @BelongsPackage:com.hyh.myshopping.filters
 * @Author:hyhWTX
 * @ClassName:QuanXianFilter
 * @CreateTime:2022年-12月-09日 21:05
 * @Description: 权限过滤器
 */
@WebFilter(urlPatterns = {"/toys/comment/addComment","/car/*"})
public class QuanXianFilter implements Filter {

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest)arg0;
        HttpServletResponse response =(HttpServletResponse)arg1;
        //获得session
        HttpSession session = request.getSession();
        //从session中获取用户的登录信息
        Object obj = session.getAttribute("curUser");
        if (obj==null){//未登录
            response.setContentType("json/application;charset=utf-8");
            PrintWriter writer = response.getWriter();
            //使用jackson将Java对象转换为JSON
            ObjectMapper mapper =new ObjectMapper();
            //将Result对象转换为JSON字符串并发送到客户端
            writer.write(mapper.writeValueAsString(Result.fail(401,"请登陆后在访问")));
            //FastJSON
            return;
        }
        //如果已登录则继续访问目标位置
        filterChain.doFilter(request,response);

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
